<!--关键词详情 -->
<template>
  <el-dialog
    v-if="keyData.result.length > 0"
    :visible.sync="dialogTableVisible"
    width="800px"
    style="margin-bottom: 24px;"
    top="24px"
    @close="handleClose"
    @open="handlerOpen"
  >
    <div slot="title" class="title">
      <p class="webfont-Medium" style="font-size: 16px;">关键词详情 (ID: {{ keyInfo.keywordId }}) </p>
      <p class="status-box" style="font-size: 14px;">
        <template>
          <!-- {{ scope.row }} -->
          <p v-if="$route.query.caStatus==='PAUSED'" style="display: flex;align-items: center;justify-content: center;">
            <i class="yellow-color status-dot" /> <span>广告系列暂停</span></p>
          <div v-else>
            <p v-if="$route.query.adStatus==='PAUSED'" style="display: flex;align-items: center;justify-content: center;">
              <i class="yellow-color status-dot" /> <span>广告组暂停</span></p>
            <div v-else>
              <!-- 判断苹果状态 -->
              <p v-if="keyInfo.status==='ACTIVE'" style="display: flex;align-items: center;justify-content: center;">
                <i class="liu-color status-dot" /><span>开启中</span></p>

              <p v-else style="display: flex;align-items: center;justify-content: center;">
                <i class="hui-color status-dot" /> <span>暂停中</span></p>
            </div>

          </div>
        </template>
      </p>
    </div>

    <div class="search-head flex">
      <div class="head-item title-item">
        <div class="sec">关键词</div>
        <div class="info">
          <el-tooltip class="item" effect="dark" :content="keyInfo.name ||keyInfo.text " placement="top">
            <span class="overflow-ellipsis webfont-Medium" v-html="keyInfo.name?replaceKeyWord(keyInfo.name):replaceKeyWord(keyInfo.text)"></span>
          </el-tooltip>

          <em>{{ keyInfo.matchType==='BROAD'?'模糊匹配':'精准匹配' }}</em>
        </div>
      </div>

      <div class="head-item ">
        <div class="sec">最高每次点击费用出价</div>
        <div class="info">
          <span class="webfont-Bold">{{ keyInfo.bidCurrency==="RMB"?'￥':'$' }}{{ keyInfo.bidAmount|$toFixed(2) }}</span>

        </div>
      </div>

    </div>

    <!-- 核心指标开始 -->
    <div class="core-box">
      <cellHeader title="核心指标" style="color: #000000;">
        <span slot="sec" style="font-size:14px ;color: rgba(51, 64, 74, 0.8);" class="webfont-Regular">(时区{{ $store.state.user.timeZone==="UTC"?'UTC':'亚洲/上海' }})</span>
        <!-- <choose-time /> -->
        <el-date-picker
          v-model="timeArrValue"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          :clearable="false"
          style="width: 230px;"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          @change="handleTimeChange"
        />
      </cellHeader>

      <el-row class="core-list" type="flex" style="flex-wrap: wrap; flex-direction: row">
        <el-col v-for="(item,index) in echartsOptions" :key="index" class="core-item" :span="6">
          <div class="item-title">{{ item.name }}</div>
          <countTo
            v-if="index==0||index==5||index==4"
            :start-val="0"
            :end-val="keyData.now[item.val]"
            :duration="1500"
            class="item-num"
            :decimals=" 2"
            :prefix="keyInfo.bidCurrency==='RMB'?'￥':'$' "
          />
          <countTo v-else-if="index<4" :start-val="0" :end-val="keyData.now[item.val]" :duration="1500" class="item-num" />
          <countTo
            v-else
            :start-val="0"
            :end-val="(item.val==='ttr'||item.val==='conversionRate')?keyData.now[item.val]*100:keyData.now[item.val]"
            :duration="1500"
            class="item-num"
            suffix="%"
          />
          <div class="item-footer">
            <!-- 日均 -->
            <p v-if="index<4" class="item-average">
              <el-tooltip class="item" effect="dark" :content="timeArrValue[0]+'至'+timeArrValue[1]+'的日均值'" placement="top">
                <span class="sec pointer ">日均{{ item.name }}</span>
              </el-tooltip>
              <span class="num"><template v-if="index==0">{{ keyInfo.bidCurrency==='RMB'?'￥':'$' }}</template>{{ average(keyData.now[item.val],keyData.result) }}</span>
            </p>

            <p class="ring">
              <huang-bi :new-val="keyData.now[item.val]*1" :old-val="keyData.old[item.val]*1" title="环比" :content="'对比'+lastCycle[0]+'至'+lastCycle[1]"></huang-bi>
            </p>

            <!-- 日环比 -->
            <!-- <p v-if="index>=4&&dayRingShow()" class="day">
              <huang-bi
                :new-val="keyData.yesterday[item.val]*1"
                :old-val="keyData.dayBeforeYesterday[item.val]*1"
                title="日环比"
                :content="'昨日对比'+beforeYesterday"
              ></huang-bi>

            </p> -->

          </div>

        </el-col>
      </el-row>

    </div>

    <!-- 核心指标开始 -->

    <el-tabs v-model="activeName" @tab-click="handleChangeTab">
      <el-tab-pane label="趋势对比" name="first">
        <!--趋势对比开始  -->
        <div class="trend-box">

          <cell-header title="趋势对比" />
          <el-radio-group v-if="false" v-model="queryData.type" size="small" style="margin-bottom: 14px;" @change="findReportKeywordTotalBySearch">
            <el-radio-button label="DAILY">每天</el-radio-button>
            <!-- <el-radio-button label="HOURLY">每小时</el-radio-button> -->
          </el-radio-group>
          <dateEchart ref="dataEchart" :date-info="keyData.result" :id-name="idName" :unit="keyInfo.bidCurrency" />
        </div>

        <!--趋势对比结束开始  -->
      </el-tab-pane>
      <el-tab-pane label="出价记录" name="second">
        <template>
          <el-table :data="tableData" style="width: 100%" :header-cell-class-name="headerStyle" @sort-change="handleSort">
            <el-table-column prop="createat" label="日期" sortable>
            </el-table-column>
            <el-table-column prop="bidamount" label="出价" align="right">
              <template slot-scope="scope">

                <span>{{ unitTxt }}{{ scope.row.bidamount|$toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="padding-top: 24px;display: flex;justify-content: flex-end;">
            <el-pagination
              :current-page="queryData.pageNum"
              :page-sizes="[10,20,30,40]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableTotoalData.length"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </template>
      </el-tab-pane>

    </el-tabs>

  </el-dialog>
</template>
<script>
import cellHeader from '@/components/cell-header.vue'
import countTo from 'vue-count-to'
import huangBi from '@/components/huangBi/index.vue'
import dateEchart from '@/components/charts/dateEchart.vue'
import {
  getsLastPeriod,
  getBeforeYes,
  includeTime
} from '@/utils/moment.js'

import {
  findReportKeywordTotal,
  findBidRecordList

} from '@/api/keyWord.js'

import {
  echartsOptions
} from '@/settings.js'
import {
  returnRing,
  returnAverage
} from '@/utils/index.js'

export default {
  name: '', // ·������
  components: {
    cellHeader,
    countTo,
    dateEchart,
    huangBi
    // chooseTime
  },

  props: {
    show: {
      type: Boolean,
      default: false
    },
    // 关键词详情
    keyInfo: {
      type: Object,
      default: function() {
        return {

        }
      }
    },
    unit: {
      type: String,
      default: function() {
        return this.$store.state.user.unit
      }
    }
  },
  data() {
    return {
      activeName: 'first',
      tableTotoalData: [],
      tableData: [],
      idName: '',
      echartsOptions,
      pickerOptions: { // 时间选择器的限制
        disabledDate(time) {
          // 不能选择今天之后的日期；
          return time.getTime() > Date.now()
        }
      },
      dialogTableVisible: false,
      value1: '',
      timeArrValue: [this.$store.state.overview.timeObj.overViewTime.startTime, this.$store.state.overview.timeObj.overViewTime
        .endTime
      ],
      queryData: {
        teamId: this.$store.state.team.teamId || '',
        currencyType: this.unit,
        adGroupId: undefined,
        campaignId: this.$route.query.campaignId,
        orgId: this.$route.query.orgId || '',
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
        type: 'DAILY',
        keywordId: undefined,
        startTime: this.$store.state.overview.timeObj.overViewTime.startTime, // 开始时间
        endTime: this.$store.state.overview.timeObj.overViewTime.endTime, // 结束时间
        prop: 'date',
        order: 'descending',
        pageNum: 1,
        pageSize: 10
      },
      keyData: {
        result: []
      } // 搜索结果
    }
  },
  computed: {
    unitTxt() {
      if (this.unit === 'RMB') return '￥'
      return '$'
    },
    // 选择的开始时间与结束时间
    timeObj() {
      // console.log(this.$store.state.overview.timeObj.overViewTime)
      return this.$store.state.overview.timeObj.overViewTime
    },
    // 上个周期的值
    lastCycle() {
      return getsLastPeriod(this.timeArrValue)
    },
    beforeYesterday() {
      return getBeforeYes()
    }
  },
  watch: {
    show: { // �����Ķ���
      deep: true, // ���ȼ�������Ϊ true
      immediate: true,
      handler: function(newV, oldV) {
        this.dialogTableVisible = newV
      }
    },
    timeObj: {
      deep: true, // ���ȼ�������Ϊ true
      immediate: true,
      handler: function(newV, oldV) {
        this.timeArrValue = [newV.startTime, newV.endTime]
        this.queryData.startTime = newV.startTime
        this.queryData.endTime = newV.endTime
        this.findReportKeywordTotalBySearch()
        this.findBidRecordList()
      }
    },

    keyInfo: {
      deep: true, // ���ȼ�������Ϊ true
      immediate: true,
      handler: function(newV, oldV) {
        this.findReportKeywordTotalBySearch()
        this.findBidRecordList()
      }
    }
  },
  // ������
  created() {
    this.idName = 'keyDateEchart' + new Date().getTime()
  },
  // ���غ�
  mounted() {

  },
  // ���ٺ�
  destroyed() {

  },

  // ����
  methods: {
    handlerOpen() {
      this.queryData.pageNum = 1
      this.timeArrValue = [this.timeObj.startTime, this.timeObj.endTime]
      this.queryData.startTime = this.timeObj.startTime
      this.queryData.endTime = this.timeObj.endTime
      this.findReportKeywordTotalBySearch()
      this.findBidRecordList()
      this.$nextTick(() => {
        if (this.$refs['dataEchart'] && this.$refs['dataEchart']['dateEchart']) {
          this.$refs['dataEchart']['dateEchart'].resize()
        }
      })
    },
    handleChangeTab(data) {
      if (data.name === 'first') {
        this.$nextTick(() => {
          if (this.$refs['dataEchart'] && this.$refs['dataEchart']['dateEchart']) {
            this.$refs['dataEchart']['dateEchart'].resize()
          }
        })
      }
      // console.log(type, '你好')
    },
    replaceKeyWord(word) {
      return word ? word.replace(/\ /g, '&nbsp;') : 'true'
    },
    headerStyle({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      if (columnIndex === 1) {
        return 'right-align'
      }
    },
    handleSort(data) {
      if (data.order) {
        this.queryData.order = data.order
      } else {
        this.queryData.order = 'descending'
      }
      this.queryData.pageNum = 1
      this.findBidRecordList()
    },

    handleSizeChange(size) {
      this.queryData.pageSize = size
      this.queryData.pageNum = 1
      this.findBidRecordList()
    },
    handleCurrentChange(num) {
      this.queryData.pageNum = num
      this.findBidRecordList()
    },

    dayRingShow() {
      return includeTime(this.timeObj.endTime)
    },
    // 计算环比
    ring(now, old) {
      const res = returnRing(now, old)
      return (res * 1).toFixed(2)
    },

    // 计算平均值
    average(num, list) {
      const res = returnAverage(num, list)
      return (res * 1).toFixed(2)
    },

    handleClose() {
      this.$emit('update:show', false)
    },
    handleTimeChange(data) {
      this.queryData.startTime = data[0]
      this.queryData.endTime = data[1]
      this.queryData.pageNum = 1
      this.findReportKeywordTotalBySearch()
      this.findBidRecordList()
    },

    async findReportKeywordTotalBySearch() {
      if (this.keyInfo.keywordId) {
        const obj = {
          ...this.queryData,
          keywordId: this.keyInfo.keywordId,
          adGroupId: this.keyInfo.adGroupId,
          teamId: this.$store.state.team.teamId || '',
		  countrySX: this.$store.state.user.timeZone, // 时区
		  timeZone: this.$store.getters.timeZoneTime // 时区比UTC时间少几个小时

        }
        const res = await findReportKeywordTotal(obj)
        const data = res.data.data
        this.keyData = data
        this.$nextTick(() => {
          // console.log(this.$refs['dataEchart'])
          if (this.$refs['dataEchart'] && this.$refs['dataEchart']['dateEchart']) {
            this.$refs['dataEchart']['dateEchart'].resize()
          }
        })
      } else {
        return false
      }
    },

    async findBidRecordList() {
      if (this.keyInfo.keywordId) {
        const obj = {
          ...this.queryData,
          keywordId: this.keyInfo.keywordId,
          adGroupId: this.keyInfo.adGroupId,
		  countrySX: this.$store.state.user.timeZone, // 时区
		  timeZone: this.$store.getters.timeZoneTime // 时区比UTC时间少几个小时

        }
        const res = await findBidRecordList(obj)
        const data = res.data.data
        this.tableTotoalData = data
        this.setTableData()
      } else {
        return false
      }
    },

    setTableData() {
      if (this.tableTotoalData.length) {
        const startNum = (this.queryData.pageNum - 1) * this.queryData.pageSize
        const endNum = this.queryData.pageNum * this.queryData.pageSize
        if (endNum > this.tableTotoalData.length) {
          this.tableData = this.tableTotoalData.slice(startNum)
        } else {
          this.tableData = this.tableTotoalData.slice(startNum, endNum)
        }
      } else {
        this.tableData = []
      }
    }

  }
}
</script>

<style scoped lang="scss">
  .title {
    p {
      display: inline-block;
      margin-right: 24px;
    }
  }

  .search-head {
    padding-bottom: 14px;
    justify-content: flex-start;
    border-bottom: 1px solid rgba(57, 68, 78, 0.1);
    margin-bottom: 24px;

    .head-item {
      width: 49%;

      .sec {
        font-size: 14px;
        line-height: 18px;
        /* identical to box height, or 129% */

        /* 此文颜色 */

        color: rgba(51, 64, 74, 0.8);
      }

      .info {
        span {
          font-size: 24px;
          line-height: 46px;
          /* identical to box height, or 192% */

          color: #000000;
        }

        em {
          font-size: 14px;
          line-height: 18px;
          padding-left: 14px;
        }
      }
    }

    .head-item.title-item {

      min-width: 260px;

      .info {
        display: flex;
        align-items: center;
        justify-content: flex-start;

        span {
          display: inline-block;
          max-width: 175px;
          /* cursor: pointer; */

        }

        em {
          margin-bottom: -6px;
        }
      }

    }
  }

  .core-box {
    border-bottom: 1px solid rgba(57, 68, 78, 0.1);;
    margin-bottom: 32px;

    .core-list {
      margin-left: -24px;

      .core-item {
        margin-bottom: 42px;
        padding-left: 24px;
        border-right: 1px solid rgba(57, 68, 78, 0.1);
        ;

        &:nth-of-type(4n) {
          border: none;
        }

        .item-title {
          font-size: 14px;
          line-height: 18px;
          /* identical to box height, or 129% */
          /* 此文颜色 */
          color: rgba(51, 64, 74, 0.8);
        }

        .item-num {
          padding-top: 4px;
          font-size: 24px;
          line-height: 46px;
          /* identical to box height, or 192% */
          /* 正文颜色 */
          color: #39444E;
          font-family: "PingFangSC-Medium", PingFangSC, sans-serif !important;

        }

        .item-footer {
          p {
            &:first-of-type {
              padding: 8px 0;
            }

            span {
              font-size: 12px;
              line-height: 16px;
            }

            .sec {
              color: #ACB6C2;
              margin-right: 12px;
            }

            .hong,
            .liu {
              color: #F31A25;
              margin-left: 12px;
            }

            .liu {
              color: #52C31C;
            }

          }
        }

      }
    }
  }

  .core-box /deep/ .el-range-editor--small .el-range__close-icon, .el-range-editor--small .el-range__icon{
    display: none;
  }
</style>
